#!/bin/bash
bot2sh="/tmp/bot_fifo_bot2sh"
sh2bot="/tmp/bot_fifo_sh2bot"
bottmp="/tmp/bot_tmp"
[ -p "$bot2sh" ] || mkfifo "$bot2sh";
[ -p "$sh2bot" ] || mkfifo "$sh2bot";

url2title(){
	curl -m 5 -r 0-1000 -s "$1" | enconv | grep "</title>" | sed -e "s/.*<title>/\n/" -e "s@</title>.*@\n@" \
	| tr -d "\n"
}
dict(){
	w3m -dump http://dict.cn/compact.php?q=$1 2>/dev/null| tac | sed '1,3d' | tac | sed -n '3,$p'
}
#url2title "$1";exit 0
if pgrep -x botcalk >/dev/null;then
pkill botcalk
sleep 3
fi

botname=`grep "room=" bot.conf | awk -F'/' '{printf("%s",$2)}'`
echo "botname=$botname"
./botcalk -f bot.conf &
#./botcalk -f bot.conf >botcalk.log&
cat "$bot2sh" | while read l;do
echo "$l" | tee -a chat.log
read nick msg <<< "$l"

if [ "$botname" == "$nick" ];then
continue
fi
#鹦鹉学舌
#if [ "$nick" != "iBot" -a "$nick" != "" ];then
#echo -n "$msg" >"$sh2bot"
#fi

#取链接标题
if echo "$msg" | grep "http://" >/dev/null ;then
	url=`echo "$msg" | awk '{for(i=0;i<=NF;i++)if($i~/^http:\/\//){printf("%s",$i);exit}}'`
	(echo -n "$nick发链接了,标题是: [" ;url2title "$url" ;echo -n "]") >"$bottmp"
	#echo "found link: $msg" 
	cat "$bottmp" >> "$sh2bot"
fi

#dict
if echo "$msg" | grep -E "^~dict" >/dev/null ;then
	en=`echo "$msg" | awk -F'[ \t!@#$%^&\`\\\\*]+' '{printf("%s",$2)}'`
	dict "$en" >"$bottmp"
	cat "$bottmp" >> "$sh2bot"
fi

#help
if echo "$msg" | grep -E "^~help" >/dev/null ;then
	cat<< EOF >> "$sh2bot"
查词: ~dict word
显示本帮助: ~help
EOF
fi
done
